/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Utility;
//


import com.sun.codemodel.JCodeModel;
import com.sun.tools.xjc.api.ErrorListener;
import com.sun.tools.xjc.api.S2JJAXBModel;
import com.sun.tools.xjc.api.SchemaCompiler;
import com.sun.tools.xjc.api.XJC;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
//
///**
// *
// * @author TOSHIBA
// */
public class XMLUtils implements Serializable {

    public static Document parseDOMFromFile(String filePath)
            throws ParserConfigurationException, SAXException, IOException {

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        File file = new File(filePath);
        Document doc = db.parse(file);
        return doc;
    }
    public static Object evaluteXPathExpression(Node node, String exp, QName typeReturn) throws XPathExpressionException{//exp la bieu thuc xpath{
        XPathFactory xf = XPathFactory.newInstance();
        XPath xpath = xf.newXPath();

        Object result = xpath.evaluate(exp, node, typeReturn);
        return result;
    }

    public static void transformDOMtoFile (Node node, String filePath) throws TransformerConfigurationException, TransformerException {
        TransformerFactory trf = TransformerFactory.newInstance();
        Transformer trans = trf.newTransformer();

        Source src = new DOMSource(node);
        File file = new File(filePath);
        Result result = new StreamResult(file);
        trans.transform(src, result);


    }

    //dung ham nay phai add jaxB library
    public static void XJCGenerateJavaObj (String output, String forcePakageName,
            String schemaPath) throws IOException {

            SchemaCompiler sc = XJC.createSchemaCompiler();
            sc.setErrorListener(new ErrorListener() {

            public void error(SAXParseException saxpe) {
                System.out.println("ERROR BY LECHAU "+ saxpe.getMessage());
            }

            public void fatalError(SAXParseException saxpe) {
                System.out.println("FATAL ERROR BY LECHAU "+ saxpe.getMessage());
            }

            public void warning(SAXParseException saxpe) {
                System.out.println("WARNING BY LECHAU "+ saxpe.getMessage());
            }

            public void info(SAXParseException saxpe) {
                System.out.println("INFO BY LECHAU "+ saxpe.getMessage());
            }
        });

        sc.forcePackageName(forcePakageName);
        File schema = new File(schemaPath);

        InputSource is = new InputSource(schema.toURI().toString());
        sc.parseSchema(is);
        S2JJAXBModel model = sc.bind();
        JCodeModel code = model.generateCode(null, null);
        code.build(new File(output));
    }
    public static Object JAXBUnmarshalling(String pakageName, String xmlPath) {
        try {
            JAXBContext jc = JAXBContext.newInstance(pakageName);
            //JAXBContext jc2 = JAXBContext.newInstance(classesToBeBound);
            Unmarshaller u = jc.createUnmarshaller();
            File f = new File(xmlPath);
            Object item  =  u.unmarshal(f);
            return item;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Object JAXBUnmarshalling(Class classesToBeBound, String xmlPath) {
        try {
            JAXBContext jc = JAXBContext.newInstance(classesToBeBound);
            Unmarshaller u = jc.createUnmarshaller();
            File f = new File(xmlPath);
            Object item  =  u.unmarshal(f);
            return item;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static void JAXBMarshalling(Object obj, String targetPath) throws JAXBException {
        JAXBContext ctx = JAXBContext.newInstance(obj.getClass());
        Marshaller mar = ctx.createMarshaller();
        mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        File file = new File(targetPath);
        mar.marshal(obj, file);
    }

//    public static Document parseDOMFromFile(String filePath) {
//        try {
//            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
//            DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
//            Document document = builder.parse(new File(filePath));
//            return document;
//        } catch (SAXException ex) {
//            Logger.getLogger(XMLUtils.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (IOException ex) {
//            Logger.getLogger(XMLUtils.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (ParserConfigurationException ex) {
//            Logger.getLogger(XMLUtils.class.getName()).log(Level.SEVERE, null, ex);
//        }
//        return null;
//    }
//
//    public static Object evaluteXPathExpression(Node node, String exp, QName typeReturn) throws XPathExpressionException {//exp la bieu thuc xpath{
//        XPathFactory xf = XPathFactory.newInstance();
//        XPath xpath = xf.newXPath();
//
//        Object result = xpath.evaluate(exp, node, typeReturn);
//        return result;
//    }
//
//    public static void transformDOMtoFile(Node node, String filePath) throws TransformerConfigurationException, TransformerException {
//        TransformerFactory trf = TransformerFactory.newInstance();
//        Transformer trans = trf.newTransformer();
//
//        Source src = new DOMSource(node);
//        File file = new File(filePath);
//        Result result = new StreamResult(file);
//        trans.transform(src, result);
//    }
//
//    //dung ham nay phai add jaxB library
//    public static void XJCGenerateJavaObj(String output, String forcePakageName,
//            String schemaPath) throws IOException {
//
//        SchemaCompiler sc = XJC.createSchemaCompiler();
//        sc.setErrorListener(new ErrorListener() {
//
//            public void error(SAXParseException saxpe) {
//                System.out.println("ERROR BY LECHAU " + saxpe.getMessage());
//            }
//
//            public void fatalError(SAXParseException saxpe) {
//                System.out.println("FATAL ERROR BY LECHAU " + saxpe.getMessage());
//            }
//
//            public void warning(SAXParseException saxpe) {
//                System.out.println("WARNING BY LECHAU " + saxpe.getMessage());
//            }
//
//            public void info(SAXParseException saxpe) {
//                System.out.println("INFO BY LECHAU " + saxpe.getMessage());
//            }
//        });
//
//        sc.forcePackageName(forcePakageName);
//        File schema = new File(schemaPath);
//
//        InputSource is = new InputSource(schema.toURI().toString());
//        sc.parseSchema(is);
//        S2JJAXBModel model = sc.bind();
//        JCodeModel code = model.generateCode(null, null);
//        code.build(new File(output));
//    }
//
//    public static Object JAXBUnmarshalling(String pakageName, String xmlPath) {
//        try {
//            JAXBContext jc = JAXBContext.newInstance(pakageName);
//            Unmarshaller u = jc.createUnmarshaller();
//            File f = new File(xmlPath);
//            Object item = u.unmarshal(f);
//            return item;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
//
//    public static void JAXBMarshalling(Object obj, String targetPath) throws JAXBException {
//        JAXBContext ctx = JAXBContext.newInstance(obj.getClass());
//        Marshaller mar = ctx.createMarshaller();
//        mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
//        mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
//        File file = new File(targetPath);
//        mar.marshal(obj, file);
//    }

    public static void marshallToJavascript(Object o, OutputStream os) {
        try {
            JAXBContext jaxbc = JAXBContext.newInstance(o.getClass());
            Marshaller marshaller = jaxbc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            marshaller.marshal(o, os);
        } catch (JAXBException ex) {
            Logger.getLogger(XMLUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
